/*
 * @Author: caihongtai caihongtai
 * @Date: 2025-02-08 21:22:56
 * @LastEditors: caihongtai caihongtai
 * @LastEditTime: 2025-03-19 10:34:18
 * @FilePath: /ai-interview-vue/src/store/modules/user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { userApi } from '@/api/user'

export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: null
    }),

    getters: {
        // 登录状态
        loginStatus: (state) => {
            // 有用户信息就表示已登录
            return !!state.userInfo
        },
        // 获取用户信息
        getUserInfo: (state) => state.userInfo
    },

    actions: {
        // 获取用户信息
        async setUserInfo() {
            try {
                const res = await userApi.getUserInfo()
                if (res.code === 0 && res.data) {
                    this.userInfo = res.data
                    return res
                }
                return null
            } catch (error) {
                console.error('获取用户信息失败:', error)
                this.userInfo = null
                return null
            }
        },

        // 登录
        async loginForm(data) {
            const res = await userApi.verifyLogin({ ...data })
            if (res.data && res.data.access_token) {
                localStorage.setItem('token', res.data.access_token)
                this.token = res.data.access_token
                // 登录成功后立即获取用户信息
                await this.setUserInfo()
                return res.data
            }
            return false
        },

        // 退出登录
        async logout() {
            let res = await userApi.logoutUser()
            if (res.code === 0) {
                localStorage.clear()
                sessionStorage.clear()
                this.token = ''
                this.userInfo = null
            } else {
                showToast(res.msg)
            }
        },

        // 更新余额
        updateBalance(amount) {
            this.balance = amount
        },

        // 检查登录状态
        checkLoginStatus() {
            const token = localStorage.getItem('token')
            if (token) {
                this.token = token
                return true
            }
            return false
        }
    },

    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user-store',
                storage: localStorage,
                paths: ['token', 'userInfo']
            }
        ]
    }
}) 